from PIL import Image, ImageDraw, ImageFont
import uuid

def generate_random_id():
    # 生成一个 UUID
    random_uuid = uuid.uuid4()
    # 将 UUID 转换为十六进制字符串并取前 16 位
    return random_uuid.hex[:16]

def text_to_image(text):
    """
    将文字转换为图片
    """
    font = ImageFont.truetype("simhei", 15, encoding='utf-8')
    img = Image.new("RGBA", ((15+2)*len(text), 50), (255, 255, 255))
      # 魔法开始，将图片画出来
    draw = ImageDraw.Draw(img)
    draw.text((0, 0), text, (0, 0, 0), font=font)
      # 保存图片
    img.save('E:\\home\\blog\\pycut2\\Image-recognition-enters-the-whiteboard\\testimage\\6c6df093482347aa.png')
    return img




def resize_image(image, target_width):
    """
    调整图片宽度，并保持比例调整高度，返回调整后的图片
    """
    width, height = image.size
    ratio = target_width / width
    new_height = int(height * ratio)
    return image.resize((target_width, new_height), Image.Resampling.NEAREST)


def merge_images_vertically(image1, image2, output_path):
    """
    将两张图片上下布局绘制为一张新图片并保存
    """
    width1, height1 = image1.size
    width2, height2 = image2.size

    # 确保两张图片宽度一致
    target_width = max(width1, width2)
    image1 = resize_image(image1, target_width)
    image2 = resize_image(image2, target_width)

    # 创建新的空白图片，高度为两张图片高度之和，宽度为统一后的宽度
    new_height = height1 + height2
    new_image = Image.new('RGB', (target_width, new_height))

    # 将第一张图片粘贴到新图片的上部
    new_image.paste(image1, (0, 0))
    # 将第二张图片粘贴到新图片的下部
    new_image.paste(image2, (0, height1))

    # 保存拼接后的新图片
    new_image.save(output_path)
    print(f"图片已成功拼接并保存到 {output_path}")



# 示例用法
# text = "#这是要转换为图片的文字#你确定吗？#这没有问题吗"
# text_image = text_to_image(text)
# image1 = text_image.resize((text_image.size[0], 45))  # 固定文字图片高度为45像素
#
# image2_path = "E:\\home\\blog\\pycut2\\Image-recognition-enters-the-whiteboard\\testimage\\6cdc492a990449e2.png"  # 替换为实际的第二张图片路径
# image2 = Image.open(image2_path)
#
# output_path = "E:\\home\\blog\\pycut2\\Image-recognition-enters-the-whiteboard\\testimage\\1.png"  # 替换为输出图片的期望保存路径
# merge_images_vertically(image1, image2, output_path)

def textandimage(text,image2):
    text_image = text_to_image(text)
    image1 = text_image.resize((text_image.size[0], 45))  # 固定文字图片高度为45像素
    output_path = f"E:\\home\\blog\\pycut2\\Image-recognition-enters-the-whiteboard\\testimage\\hebin_{generate_random_id()}.png"  # 替换为输出图片的期望保存路径
    merge_images_vertically(image1, image2, output_path)
    return output_path
